

<!DOCTYPE html>
<html lang="zh-CN" data-default-color-scheme=auto>



<head>
  <meta charset="UTF-8">
  <link rel="apple-touch-icon" sizes="76x76" href="/hh1247857703/BlogOfHH.git/img/favicon.png">
  <link rel="icon" href="/hh1247857703/BlogOfHH.git/img/favicon.png">
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, shrink-to-fit=no">
  <meta http-equiv="x-ua-compatible" content="ie=edge">
  
  <meta name="theme-color" content="#2f4154">
  <meta name="author" content="HH">
  <meta name="keywords" content="">
  
    <meta name="description" content="直接上代码123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101">
<meta property="og:type" content="article">
<meta property="og:title" content="RSA加密解密.md">
<meta property="og:url" content="https://gitee.com/hh1247857703/BlogOfHH.git/2022/04/01/java/RSA%E5%8A%A0%E5%AF%86%E8%A7%A3%E5%AF%86/index.html">
<meta property="og:site_name" content="The Blog Of HH">
<meta property="og:description" content="直接上代码123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101">
<meta property="og:locale" content="zh_CN">
<meta property="article:published_time" content="2022-04-01T11:56:20.000Z">
<meta property="article:modified_time" content="2022-04-01T11:59:36.530Z">
<meta property="article:author" content="HH">
<meta name="twitter:card" content="summary_large_image">
  
  
  <title>RSA加密解密.md - The Blog Of HH</title>

  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/css/bootstrap.min.css" />


  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/github-markdown-css@4/github-markdown.min.css" />
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/hint.css@2/hint.min.css" />

  
    
    
      
      <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/highlight.js@10/styles/arta.min.css" />
    
  

  
    <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.css" />
  


<!-- 主题依赖的图标库，不要自行修改 -->

<link rel="stylesheet" href="//at.alicdn.com/t/font_1749284_ba1fz6golrf.css">



<link rel="stylesheet" href="//at.alicdn.com/t/font_1736178_lbnruvf0jn.css">


<link  rel="stylesheet" href="/hh1247857703/BlogOfHH.git/css/main.css" />

<!-- 自定义样式保持在最底部 -->


  <script id="fluid-configs">
    var Fluid = window.Fluid || {};
    var CONFIG = {"hostname":"gitee.com","root":"/hh1247857703/BlogOfHH.git/","version":"1.8.14","typing":{"enable":true,"typeSpeed":130,"cursorChar":"💨","loop":false},"anchorjs":{"enable":true,"element":"h1,h2,h3,h4,h5,h6","placement":"right","visible":"hover","icon":"❡"},"progressbar":{"enable":true,"height_px":3,"color":"#29d","options":{"showSpinner":false,"trickleSpeed":100}},"copy_btn":true,"image_zoom":{"enable":true,"img_url_replace":["",""]},"toc":{"enable":true,"headingSelector":"h1,h2,h3,h4,h5,h6","collapseDepth":0},"lazyload":{"enable":true,"loading_img":"/img/loading/loading.gif","onlypost":false,"offset_factor":2},"web_analytics":{"enable":true,"baidu":17795511,"google":null,"gtag":null,"tencent":{"sid":null,"cid":null},"woyaola":null,"cnzz":null,"leancloud":{"app_id":null,"app_key":null,"server_url":null,"path":"window.location.pathname","ignore_local":false}},"search_path":"/hh1247857703/BlogOfHH.git/local-search.xml"};
  </script>
  <script  src="/hh1247857703/BlogOfHH.git/js/utils.js" ></script>
  <script  src="/hh1247857703/BlogOfHH.git/js/color-schema.js" ></script>
<meta name="generator" content="Hexo 6.1.0"></head>


<body>
  <header style="height: 70vh;">
    <nav id="navbar" class="navbar fixed-top  navbar-expand-lg navbar-dark scrolling-navbar">
  <div class="container">
    <a class="navbar-brand" href="/hh1247857703/BlogOfHH.git/">
      <strong>Smile Everyday!</strong>
    </a>

    <button id="navbar-toggler-btn" class="navbar-toggler" type="button" data-toggle="collapse"
            data-target="#navbarSupportedContent"
            aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
      <div class="animated-icon"><span></span><span></span><span></span></div>
    </button>

    <!-- Collapsible content -->
    <div class="collapse navbar-collapse" id="navbarSupportedContent">
      <ul class="navbar-nav ml-auto text-center">
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/hh1247857703/BlogOfHH.git/">
                <i class="iconfont icon-home-fill"></i>
                首页
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/hh1247857703/BlogOfHH.git/archives/">
                <i class="iconfont icon-archive-fill"></i>
                归档
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/hh1247857703/BlogOfHH.git/categories/">
                <i class="iconfont icon-category-fill"></i>
                分类
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/hh1247857703/BlogOfHH.git/about/">
                <i class="iconfont icon-user-fill"></i>
                关于
              </a>
            </li>
          
        
          
          
          
          
            <li class="nav-item">
              <a class="nav-link" href="/hh1247857703/BlogOfHH.git/links/">
                <i class="iconfont icon-link-fill"></i>
                友链
              </a>
            </li>
          
        
        
          <li class="nav-item" id="search-btn">
            <a class="nav-link" target="_self" href="javascript:;" data-toggle="modal" data-target="#modalSearch" aria-label="Search">
              &nbsp;<i class="iconfont icon-search"></i>&nbsp;
            </a>
          </li>
        
        
          <li class="nav-item" id="color-toggle-btn">
            <a class="nav-link" target="_self" href="javascript:;" aria-label="Color Toggle">&nbsp;<i
                class="iconfont icon-dark" id="color-toggle-icon"></i>&nbsp;</a>
          </li>
        
      </ul>
    </div>
  </div>
</nav>

    <div class="banner" id="banner" parallax=true
         style="background: url('/hh1247857703/BlogOfHH.git/img/allbg.png') no-repeat center center;
           background-size: cover;">
      <div class="full-bg-img">
        <div class="mask flex-center" style="background-color: rgba(0, 0, 0, 0.3)">
          <div class="page-header text-center fade-in-up">
            <span class="h2" id="subtitle" title="RSA加密解密.md">
              
            </span>

            
              <div class="mt-3">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-author" aria-hidden="true"></i>
      HH
    </span>
  
  
    <span class="post-meta">
      <i class="iconfont icon-date-fill" aria-hidden="true"></i>
      <time datetime="2022-04-01 19:56" pubdate>
        2022年4月1日 晚上
      </time>
    </span>
  
</div>

<div class="mt-1">
  
    <span class="post-meta mr-2">
      <i class="iconfont icon-chart"></i>
      5.9k 字
    </span>
  

  
    <span class="post-meta mr-2">
      <i class="iconfont icon-clock-fill"></i>
      
      
      49 分钟
    </span>
  

  
  
    
      <!-- 不蒜子统计文章PV -->
      <span id="busuanzi_container_page_pv" style="display: none">
        <i class="iconfont icon-eye" aria-hidden="true"></i>
        <span id="busuanzi_value_page_pv"></span> 次
      </span>
    
  
</div>

            
          </div>

          
        </div>
      </div>
    </div>
  </header>

  <main>
    
      

<div class="container-fluid nopadding-x">
  <div class="row nomargin-x">
    <div class="d-none d-lg-block col-lg-2"></div>
    <div class="col-lg-8 nopadding-x-md">
      <div class="container nopadding-x-md" id="board-ctn">
        <div class="py-5" id="board">
          <article class="post-content mx-auto">
            <!-- SEO header -->
            <h1 style="display: none">RSA加密解密.md</h1>
            
              <p class="note note-info">
                
                  本文最后更新于：15 小时前
                
              </p>
            
            <div class="markdown-body">
              <h2 id="直接上代码"><a href="#直接上代码" class="headerlink" title="直接上代码"></a>直接上代码</h2><figure class="highlight java"><table><tr><td class="gutter"><div class="code-wrapper"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br><span class="line">71</span><br><span class="line">72</span><br><span class="line">73</span><br><span class="line">74</span><br><span class="line">75</span><br><span class="line">76</span><br><span class="line">77</span><br><span class="line">78</span><br><span class="line">79</span><br><span class="line">80</span><br><span class="line">81</span><br><span class="line">82</span><br><span class="line">83</span><br><span class="line">84</span><br><span class="line">85</span><br><span class="line">86</span><br><span class="line">87</span><br><span class="line">88</span><br><span class="line">89</span><br><span class="line">90</span><br><span class="line">91</span><br><span class="line">92</span><br><span class="line">93</span><br><span class="line">94</span><br><span class="line">95</span><br><span class="line">96</span><br><span class="line">97</span><br><span class="line">98</span><br><span class="line">99</span><br><span class="line">100</span><br><span class="line">101</span><br><span class="line">102</span><br><span class="line">103</span><br><span class="line">104</span><br><span class="line">105</span><br><span class="line">106</span><br><span class="line">107</span><br><span class="line">108</span><br><span class="line">109</span><br><span class="line">110</span><br><span class="line">111</span><br><span class="line">112</span><br><span class="line">113</span><br><span class="line">114</span><br><span class="line">115</span><br><span class="line">116</span><br><span class="line">117</span><br><span class="line">118</span><br><span class="line">119</span><br><span class="line">120</span><br><span class="line">121</span><br><span class="line">122</span><br><span class="line">123</span><br><span class="line">124</span><br><span class="line">125</span><br><span class="line">126</span><br><span class="line">127</span><br><span class="line">128</span><br><span class="line">129</span><br><span class="line">130</span><br><span class="line">131</span><br><span class="line">132</span><br><span class="line">133</span><br><span class="line">134</span><br><span class="line">135</span><br><span class="line">136</span><br><span class="line">137</span><br><span class="line">138</span><br><span class="line">139</span><br><span class="line">140</span><br><span class="line">141</span><br><span class="line">142</span><br><span class="line">143</span><br><span class="line">144</span><br><span class="line">145</span><br><span class="line">146</span><br><span class="line">147</span><br><span class="line">148</span><br><span class="line">149</span><br><span class="line">150</span><br><span class="line">151</span><br><span class="line">152</span><br><span class="line">153</span><br><span class="line">154</span><br><span class="line">155</span><br><span class="line">156</span><br><span class="line">157</span><br><span class="line">158</span><br><span class="line">159</span><br><span class="line">160</span><br><span class="line">161</span><br><span class="line">162</span><br><span class="line">163</span><br><span class="line">164</span><br><span class="line">165</span><br><span class="line">166</span><br><span class="line">167</span><br><span class="line">168</span><br><span class="line">169</span><br><span class="line">170</span><br><span class="line">171</span><br><span class="line">172</span><br><span class="line">173</span><br><span class="line">174</span><br><span class="line">175</span><br><span class="line">176</span><br><span class="line">177</span><br><span class="line">178</span><br><span class="line">179</span><br><span class="line">180</span><br><span class="line">181</span><br><span class="line">182</span><br><span class="line">183</span><br><span class="line">184</span><br><span class="line">185</span><br><span class="line">186</span><br><span class="line">187</span><br><span class="line">188</span><br><span class="line">189</span><br><span class="line">190</span><br><span class="line">191</span><br><span class="line">192</span><br><span class="line">193</span><br><span class="line">194</span><br><span class="line">195</span><br><span class="line">196</span><br><span class="line">197</span><br><span class="line">198</span><br><span class="line">199</span><br><span class="line">200</span><br><span class="line">201</span><br><span class="line">202</span><br></pre></div></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">package</span> com.kite;<br><br><span class="hljs-keyword">import</span> java.io.ByteArrayOutputStream;<br><span class="hljs-keyword">import</span> java.io.File;<br><span class="hljs-keyword">import</span> java.io.FileOutputStream;<br><span class="hljs-keyword">import</span> java.nio.charset.StandardCharsets;<br><span class="hljs-keyword">import</span> java.security.KeyFactory;<br><span class="hljs-keyword">import</span> java.security.KeyPair;<br><span class="hljs-keyword">import</span> java.security.KeyPairGenerator;<br><span class="hljs-keyword">import</span> java.security.PrivateKey;<br><span class="hljs-keyword">import</span> java.security.PublicKey;<br><span class="hljs-keyword">import</span> java.security.Signature;<br><span class="hljs-keyword">import</span> java.security.spec.PKCS8EncodedKeySpec;<br><span class="hljs-keyword">import</span> java.security.spec.X509EncodedKeySpec;<br><span class="hljs-keyword">import</span> javax.crypto.Cipher;<br><span class="hljs-keyword">import</span> org.apache.commons.codec.binary.Base64;<br><br><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">TestRSA</span> &#123;<br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * RSA最大加密明文大小</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> <span class="hljs-variable">MAX_ENCRYPT_BLOCK</span> <span class="hljs-operator">=</span> <span class="hljs-number">117</span>;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * RSA最大解密密文大小</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">int</span> <span class="hljs-variable">MAX_DECRYPT_BLOCK</span> <span class="hljs-operator">=</span> <span class="hljs-number">128</span>;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 获取密钥对</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span> 密钥对</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> KeyPair <span class="hljs-title function_">getKeyPair</span><span class="hljs-params">()</span> <span class="hljs-keyword">throws</span> Exception &#123;<br>        <span class="hljs-type">KeyPairGenerator</span> <span class="hljs-variable">generator</span> <span class="hljs-operator">=</span> KeyPairGenerator.getInstance(<span class="hljs-string">&quot;RSA&quot;</span>);<br>        generator.initialize(<span class="hljs-number">1024</span>);<br>        <span class="hljs-keyword">return</span> generator.generateKeyPair();<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 获取私钥</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> privateKey 私钥字符串</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span></span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> PrivateKey <span class="hljs-title function_">getPrivateKey</span><span class="hljs-params">(String privateKey)</span> <span class="hljs-keyword">throws</span> Exception &#123;<br>        <span class="hljs-type">KeyFactory</span> <span class="hljs-variable">keyFactory</span> <span class="hljs-operator">=</span> KeyFactory.getInstance(<span class="hljs-string">&quot;RSA&quot;</span>);<br>        <span class="hljs-type">byte</span>[] decodedKey = Base64.decodeBase64(privateKey.getBytes());<br>        <span class="hljs-type">PKCS8EncodedKeySpec</span> <span class="hljs-variable">keySpec</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">PKCS8EncodedKeySpec</span>(decodedKey);<br>        <span class="hljs-keyword">return</span> keyFactory.generatePrivate(keySpec);<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 获取公钥</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> publicKey 公钥字符串</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span></span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> PublicKey <span class="hljs-title function_">getPublicKey</span><span class="hljs-params">(String publicKey)</span> <span class="hljs-keyword">throws</span> Exception &#123;<br>        <span class="hljs-type">KeyFactory</span> <span class="hljs-variable">keyFactory</span> <span class="hljs-operator">=</span> KeyFactory.getInstance(<span class="hljs-string">&quot;RSA&quot;</span>);<br>        <span class="hljs-type">byte</span>[] decodedKey = Base64.decodeBase64(publicKey.getBytes());<br>        <span class="hljs-type">X509EncodedKeySpec</span> <span class="hljs-variable">keySpec</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">X509EncodedKeySpec</span>(decodedKey);<br>        <span class="hljs-keyword">return</span> keyFactory.generatePublic(keySpec);<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * RSA加密</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> data 待加密数据</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> publicKey 公钥</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span></span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> String <span class="hljs-title function_">encrypt</span><span class="hljs-params">(String data, PublicKey publicKey)</span> <span class="hljs-keyword">throws</span> Exception &#123;<br>        <span class="hljs-type">Cipher</span> <span class="hljs-variable">cipher</span> <span class="hljs-operator">=</span> Cipher.getInstance(<span class="hljs-string">&quot;RSA&quot;</span>);<br>        cipher.init(Cipher.ENCRYPT_MODE, publicKey);<br>        <span class="hljs-type">int</span> <span class="hljs-variable">inputLen</span> <span class="hljs-operator">=</span> data.getBytes().length;<br>        <span class="hljs-type">ByteArrayOutputStream</span> <span class="hljs-variable">out</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">ByteArrayOutputStream</span>();<br>        <span class="hljs-type">int</span> <span class="hljs-variable">offset</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;<br>        <span class="hljs-type">byte</span>[] cache;<br>        <span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;<br>        <span class="hljs-comment">// 对数据分段加密</span><br>        <span class="hljs-keyword">while</span> (inputLen - offset &gt; <span class="hljs-number">0</span>) &#123;<br>            <span class="hljs-keyword">if</span> (inputLen - offset &gt; MAX_ENCRYPT_BLOCK) &#123;<br>                cache = cipher.doFinal(data.getBytes(), offset, MAX_ENCRYPT_BLOCK);<br>            &#125; <span class="hljs-keyword">else</span> &#123;<br>                cache = cipher.doFinal(data.getBytes(), offset, inputLen - offset);<br>            &#125;<br>            out.write(cache, <span class="hljs-number">0</span>, cache.length);<br>            i++;<br>            offset = i * MAX_ENCRYPT_BLOCK;<br>        &#125;<br>        <span class="hljs-type">byte</span>[] encryptedData = out.toByteArray();<br>        out.close();<br>        <span class="hljs-comment">// 获取加密内容使用base64进行编码,并以UTF-8为标准转化成字符串</span><br>        <span class="hljs-comment">// 加密后的字符串</span><br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(Base64.encodeBase64String(encryptedData));<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * RSA解密</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> data 待解密数据</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> privateKey 私钥</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span></span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> String <span class="hljs-title function_">decrypt</span><span class="hljs-params">(String data, PrivateKey privateKey)</span> <span class="hljs-keyword">throws</span> Exception &#123;<br>        <span class="hljs-type">Cipher</span> <span class="hljs-variable">cipher</span> <span class="hljs-operator">=</span> Cipher.getInstance(<span class="hljs-string">&quot;RSA&quot;</span>);<br>        cipher.init(Cipher.DECRYPT_MODE, privateKey);<br>        <span class="hljs-type">byte</span>[] dataBytes = Base64.decodeBase64(data);<br>        <span class="hljs-type">int</span> <span class="hljs-variable">inputLen</span> <span class="hljs-operator">=</span> dataBytes.length;<br>        <span class="hljs-type">ByteArrayOutputStream</span> <span class="hljs-variable">out</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">ByteArrayOutputStream</span>();<br>        <span class="hljs-type">int</span> <span class="hljs-variable">offset</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;<br>        <span class="hljs-type">byte</span>[] cache;<br>        <span class="hljs-type">int</span> <span class="hljs-variable">i</span> <span class="hljs-operator">=</span> <span class="hljs-number">0</span>;<br>        <span class="hljs-comment">// 对数据分段解密</span><br>        <span class="hljs-keyword">while</span> (inputLen - offset &gt; <span class="hljs-number">0</span>) &#123;<br>            <span class="hljs-keyword">if</span> (inputLen - offset &gt; MAX_DECRYPT_BLOCK) &#123;<br>                cache = cipher.doFinal(dataBytes, offset, MAX_DECRYPT_BLOCK);<br>            &#125; <span class="hljs-keyword">else</span> &#123;<br>                cache = cipher.doFinal(dataBytes, offset, inputLen - offset);<br>            &#125;<br>            out.write(cache, <span class="hljs-number">0</span>, cache.length);<br>            i++;<br>            offset = i * MAX_DECRYPT_BLOCK;<br>        &#125;<br>        <span class="hljs-type">byte</span>[] decryptedData = out.toByteArray();<br>        out.close();<br>        <span class="hljs-comment">// 解密后的内容</span><br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(decryptedData, <span class="hljs-string">&quot;UTF-8&quot;</span>);<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 签名</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> data 待签名数据</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> privateKey 私钥</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span> 签名</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> String <span class="hljs-title function_">sign</span><span class="hljs-params">(String data, PrivateKey privateKey)</span> <span class="hljs-keyword">throws</span> Exception &#123;<br>        <span class="hljs-type">byte</span>[] keyBytes = privateKey.getEncoded();<br>        <span class="hljs-type">PKCS8EncodedKeySpec</span> <span class="hljs-variable">keySpec</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">PKCS8EncodedKeySpec</span>(keyBytes);<br>        <span class="hljs-type">KeyFactory</span> <span class="hljs-variable">keyFactory</span> <span class="hljs-operator">=</span> KeyFactory.getInstance(<span class="hljs-string">&quot;RSA&quot;</span>);<br>        <span class="hljs-type">PrivateKey</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> keyFactory.generatePrivate(keySpec);<br>        <span class="hljs-type">Signature</span> <span class="hljs-variable">signature</span> <span class="hljs-operator">=</span> Signature.getInstance(<span class="hljs-string">&quot;MD5withRSA&quot;</span>);<br>        signature.initSign(key);<br>        signature.update(data.getBytes());<br>        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(Base64.encodeBase64(signature.sign()));<br>    &#125;<br><br>    <span class="hljs-comment">/**</span><br><span class="hljs-comment">     * 验签</span><br><span class="hljs-comment">     *</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> srcData 原始字符串</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> publicKey 公钥</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@param</span> sign 签名</span><br><span class="hljs-comment">     * <span class="hljs-doctag">@return</span> 是否验签通过</span><br><span class="hljs-comment">     */</span><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-type">boolean</span> <span class="hljs-title function_">verify</span><span class="hljs-params">(String srcData, PublicKey publicKey, String sign)</span> <span class="hljs-keyword">throws</span> Exception &#123;<br>        <span class="hljs-type">byte</span>[] keyBytes = publicKey.getEncoded();<br>        <span class="hljs-type">X509EncodedKeySpec</span> <span class="hljs-variable">keySpec</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">X509EncodedKeySpec</span>(keyBytes);<br>        <span class="hljs-type">KeyFactory</span> <span class="hljs-variable">keyFactory</span> <span class="hljs-operator">=</span> KeyFactory.getInstance(<span class="hljs-string">&quot;RSA&quot;</span>);<br>        <span class="hljs-type">PublicKey</span> <span class="hljs-variable">key</span> <span class="hljs-operator">=</span> keyFactory.generatePublic(keySpec);<br>        <span class="hljs-type">Signature</span> <span class="hljs-variable">signature</span> <span class="hljs-operator">=</span> Signature.getInstance(<span class="hljs-string">&quot;MD5withRSA&quot;</span>);<br>        signature.initVerify(key);<br>        signature.update(srcData.getBytes());<br>        <span class="hljs-keyword">return</span> signature.verify(Base64.decodeBase64(sign.getBytes()));<br>    &#125;<br><br>    <span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title function_">main</span><span class="hljs-params">(String[] args)</span> &#123;<br>        <span class="hljs-keyword">try</span> &#123;<br>            <span class="hljs-comment">// 生成密钥对</span><br>            <span class="hljs-type">KeyPair</span> <span class="hljs-variable">keyPair</span> <span class="hljs-operator">=</span> getKeyPair();<br>            <span class="hljs-type">String</span> <span class="hljs-variable">privateKey</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(Base64.encodeBase64(keyPair.getPrivate().getEncoded()));<br>            <span class="hljs-type">String</span> <span class="hljs-variable">publicKey</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">String</span>(Base64.encodeBase64(keyPair.getPublic().getEncoded()));<br><br>            <span class="hljs-type">File</span> <span class="hljs-variable">file</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">File</span>(<span class="hljs-string">&quot;D:\\IdeaWorkplaces\\kite-server\\rsa.txt&quot;</span>);<br>            <span class="hljs-type">FileOutputStream</span> <span class="hljs-variable">stream</span> <span class="hljs-operator">=</span> <span class="hljs-keyword">new</span> <span class="hljs-title class_">FileOutputStream</span>(file, <span class="hljs-literal">true</span>);<br><br>            <span class="hljs-type">String</span> <span class="hljs-variable">privateKeyTxt</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;私钥: == &quot;</span> + privateKey + <span class="hljs-string">&quot;\n&quot;</span>;<br>            <span class="hljs-type">String</span> <span class="hljs-variable">publicKeyText</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;公钥: == &quot;</span> + publicKey;<br>            stream.write(privateKeyTxt.getBytes(StandardCharsets.UTF_8));<br>            stream.write(publicKeyText.getBytes(StandardCharsets.UTF_8));<br><br>            <span class="hljs-comment">// RSA加密</span><br>            <span class="hljs-type">String</span> <span class="hljs-variable">data</span> <span class="hljs-operator">=</span> <span class="hljs-string">&quot;待加密的文字内容&quot;</span>;<br>            <span class="hljs-type">String</span> <span class="hljs-variable">encryptData</span> <span class="hljs-operator">=</span> encrypt(data, getPublicKey(publicKey));<br>            System.out.println(<span class="hljs-string">&quot;加密后内容:&quot;</span> + encryptData);<br>            <span class="hljs-comment">// RSA解密</span><br>            <span class="hljs-type">String</span> <span class="hljs-variable">decryptData</span> <span class="hljs-operator">=</span> decrypt(encryptData, getPrivateKey(privateKey));<br>            System.out.println(<span class="hljs-string">&quot;解密后内容:&quot;</span> + decryptData);<br><br>            <span class="hljs-comment">// RSA签名</span><br>            <span class="hljs-type">String</span> <span class="hljs-variable">sign</span> <span class="hljs-operator">=</span> sign(data, getPrivateKey(privateKey));<br>            <span class="hljs-comment">// RSA验签</span><br>            <span class="hljs-type">boolean</span> <span class="hljs-variable">result</span> <span class="hljs-operator">=</span> verify(data, getPublicKey(publicKey), sign);<br>            System.out.print(<span class="hljs-string">&quot;验签结果:&quot;</span> + result);<br>        &#125; <span class="hljs-keyword">catch</span> (Exception e) &#123;<br>            e.printStackTrace();<br>            System.out.print(<span class="hljs-string">&quot;加解密异常&quot;</span>);<br>        &#125;<br>    &#125;<br>&#125;<br></code></pre></td></tr></table></figure>
            </div>
            <hr>
            <div>
              <div class="post-metas mb-3">
                
                  <div class="post-meta mr-3">
                    <i class="iconfont icon-category"></i>
                    
                      <a class="hover-with-bg" href="/hh1247857703/BlogOfHH.git/categories/Java/">Java</a>
                    
                  </div>
                
                
              </div>
              
                <p class="note note-warning">
                  
                    本博客所有文章除特别声明外，均采用 <a target="_blank" href="https://creativecommons.org/licenses/by-sa/4.0/deed.zh" rel="nofollow noopener noopener">CC BY-SA 4.0 协议</a> ，转载请注明出处！
                  
                </p>
              
              
                <div class="post-prevnext">
                  <article class="post-prev col-6">
                    
                    
                  </article>
                  <article class="post-next col-6">
                    
                    
                      <a href="/hh1247857703/BlogOfHH.git/2022/03/31/java/%E7%BB%9F%E4%B8%80%E5%BC%82%E5%B8%B8%E5%85%A8%E5%B1%80%E5%A4%84%E7%90%86/">
                        <span class="hidden-mobile">统一异常全局处理.md</span>
                        <span class="visible-mobile">下一篇</span>
                        <i class="iconfont icon-arrowright"></i>
                      </a>
                    
                  </article>
                </div>
              
            </div>

            
              <!-- Comments -->
              <article class="comments" id="comments" lazyload>
                
                  
                
                
  <div id="valine"></div>
  <script type="text/javascript">
    Fluid.utils.loadComments('#valine', function() {
      Fluid.utils.createScript('https://cdn.jsdelivr.net/npm/valine@1/dist/Valine.min.js', function() {
        var options = Object.assign(
          {"appId":"YNaQpUHmK70UWg4eAuxASf1T-gzGzoHsz","appKey":"e0uHoSbv8bBD5Jruur36RDvW","path":"window.location.pathname","placeholder":null,"avatar":"robohash","meta":["nick","mail","link"],"requiredFields":[],"pageSize":10,"lang":"zh-CN","highlight":false,"recordIP":false,"serverURLs":"","emojiCDN":null,"emojiMaps":null,"enableQQ":false},
          {
            el: "#valine",
            path: window.location.pathname
          }
        )
        new Valine(options);
        Fluid.utils.waitElementVisible('#valine .vcontent', () => {
          Fluid.plugins.initFancyBox('#valine .vcontent img:not(.vemoji)');
        })
      });
    });
  </script>
  <noscript>Please enable JavaScript to view the comments</noscript>


              </article>
            
          </article>
        </div>
      </div>
    </div>
    
      <div class="d-none d-lg-block col-lg-2 toc-container" id="toc-ctn">
        <div id="toc">
  <p class="toc-header"><i class="iconfont icon-list"></i>&nbsp;目录</p>
  <div class="toc-body" id="toc-body"></div>
</div>

      </div>
    
  </div>
</div>

<!-- Custom -->


    

    
      <a id="scroll-top-button" aria-label="TOP" href="#" role="button">
        <i class="iconfont icon-arrowup" aria-hidden="true"></i>
      </a>
    

    
      <div class="modal fade" id="modalSearch" tabindex="-1" role="dialog" aria-labelledby="ModalLabel"
     aria-hidden="true">
  <div class="modal-dialog modal-dialog-scrollable modal-lg" role="document">
    <div class="modal-content">
      <div class="modal-header text-center">
        <h4 class="modal-title w-100 font-weight-bold">搜索</h4>
        <button type="button" id="local-search-close" class="close" data-dismiss="modal" aria-label="Close">
          <span aria-hidden="true">&times;</span>
        </button>
      </div>
      <div class="modal-body mx-3">
        <div class="md-form mb-5">
          <input type="text" id="local-search-input" class="form-control validate">
          <label data-error="x" data-success="v"
                 for="local-search-input">关键词</label>
        </div>
        <div class="list-group" id="local-search-result"></div>
      </div>
    </div>
  </div>
</div>
    

    
  </main>

  <footer class="text-center mt-5 py-3">
  <div class="footer-content">
     <a href="https://hexo.io" target="_blank" rel="nofollow noopener"><span>本网站使用Fluid主题</span></a> <i class="iconfont icon-love"></i> <a href="https://github.com/fluid-dev/hexo-theme-fluid" target="_blank" rel="nofollow noopener"><span>Fluid</span></a> 
  </div>
  
  <div class="statistics">
    
    

    
      
        <!-- 不蒜子统计PV -->
        <span id="busuanzi_container_site_pv" style="display: none">
            总访问量 
            <span id="busuanzi_value_site_pv"></span>
             次
          </span>
      
      
        <!-- 不蒜子统计UV -->
        <span id="busuanzi_container_site_uv" style="display: none">
            总访客数 
            <span id="busuanzi_value_site_uv"></span>
             人
          </span>
      
    
  </div>


  

  
</footer>


  <!-- SCRIPTS -->
  
  <script  src="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.js" ></script>
  <link  rel="stylesheet" href="https://cdn.jsdelivr.net/npm/nprogress@0/nprogress.min.css" />

  <script>
    NProgress.configure({"showSpinner":false,"trickleSpeed":100})
    NProgress.start()
    window.addEventListener('load', function() {
      NProgress.done();
    })
  </script>


<script  src="https://cdn.jsdelivr.net/npm/jquery@3/dist/jquery.min.js" ></script>
<script  src="https://cdn.jsdelivr.net/npm/bootstrap@4/dist/js/bootstrap.min.js" ></script>
<script  src="/hh1247857703/BlogOfHH.git/js/events.js" ></script>
<script  src="/hh1247857703/BlogOfHH.git/js/plugins.js" ></script>

<!-- Plugins -->


  <script  src="/hh1247857703/BlogOfHH.git/js/local-search.js" ></script>



  
    <script  src="/hh1247857703/BlogOfHH.git/js/img-lazyload.js" ></script>
  



  



  
    <script  src="https://cdn.jsdelivr.net/npm/tocbot@4/dist/tocbot.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/@fancyapps/fancybox@3/dist/jquery.fancybox.min.js" ></script>
  
  
    <script  src="https://cdn.jsdelivr.net/npm/anchor-js@4/anchor.min.js" ></script>
  
  
    <script defer src="https://cdn.jsdelivr.net/npm/clipboard@2/dist/clipboard.min.js" ></script>
  



  <script defer src="https://busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js" ></script>




  <script  src="https://cdn.jsdelivr.net/npm/typed.js@2/lib/typed.min.js" ></script>
  <script>
    (function (window, document) {
      var typing = Fluid.plugins.typing;
      var title = document.getElementById('subtitle').title;
      
        typing(title);
      
    })(window, document);
  </script>












  
    <!-- Baidu Analytics -->
    <script defer>
      var _hmt = _hmt || [];
      (function () {
        var hm = document.createElement("script");
        hm.src = "https://hm.baidu.com/hm.js?17795511";
        var s = document.getElementsByTagName("script")[0];
        s.parentNode.insertBefore(hm, s);
      })();
    </script>
  

  

  

  

  

  





<!-- 主题的启动项 保持在最底部 -->
<script  src="/hh1247857703/BlogOfHH.git/js/boot.js" ></script>


</body>
</html>
